package be.tihh.mgmt.gui;

import be.tihh.mgmt.gui.util.TaskListIconListCellRenderer;
import be.tihh.mgmt.gui.xml.computers.Computer;
import be.tihh.mgmt.tasks.Task;

import javax.swing.*;
import java.util.ArrayList;

public class ComputerDetailRefresher implements Runnable{

    private ComputerDetail computerDetail;

    public ComputerDetailRefresher(ComputerDetail computerDetail) {
        this.computerDetail = computerDetail;
    }

    public void run() {
        while(true){//todo : does this have to run all the time?
            if(computerDetail.getComputer()!=null){
                refreshTasksList();
                refreshTaskStatus();
            }
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    private void refreshTaskStatus() {
        String status;
        ArrayList<Task> tasks = computerDetail.getComputer().getTasks();
        if(tasks.size()>0){
            status = tasks.get(0).getTaskStatus().getStatus();
        }else{
            status = "No Tasks";
        }
        computerDetail.getStatusTextField().setText(status);
    }

    public void refreshTasksList() {
        DefaultListModel model = new DefaultListModel();
        Computer computer = computerDetail.getComputer();
        try {
            for (int i = 0; i < computer.getTasks().size(); i++) {
                Task task = computer.getTasks().get(i);
                model.addElement(task);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        computerDetail.getTaskList().setModel(model);
        ListCellRenderer listCellRenderer = new TaskListIconListCellRenderer();
        computerDetail.getTaskList().setCellRenderer(listCellRenderer);
    }

}
